package demos;


import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class NumSource {
    private int number = 0;
    Lock lock = new ReentrantLock();
    Condition condition = lock.newCondition();

    public void increment() {
        lock.lock();
        try {
            while (number != 0) {// 由于await使得线程进入阻塞态，是交出处理机的，下一次仍要重新判断一次，防止虚假唤醒
                condition.await();
            }
            number++;
            condition.signalAll();
            System.out.println(Thread.currentThread().getName() + "\t" + number);
        } catch (Exception e) { e.printStackTrace(); } finally {
            lock.unlock();
        }
    }

    public void decrement() {
        lock.lock();
        try {
            while (number == 0) {
                condition.await();
            }
            number--;
            condition.signalAll();
            System.out.println(Thread.currentThread().getName() + "\t" + number);
        } catch (Exception e) { e.printStackTrace(); } finally {
            lock.unlock();
        }
    }
}


/**
 * 1. 线程操作资源类
 * 2. 判断/干活/通知
 * 3. 多线程交互中，要防止多线程的虚假唤醒，即循环判断
 *
 */
public class WaitNotifyDemo {
    public static void main(String[] args) {
        NumSource src = new NumSource();
        new Thread(() -> { for (int i = 0; i < 10; ++i) src.increment(); }, "A").start();
        new Thread(() -> { for (int i = 0; i < 10; ++i) src.decrement(); }, "B").start();
        new Thread(() -> { for (int i = 0; i < 10; ++i) src.increment(); }, "C").start();
        new Thread(() -> { for (int i = 0; i < 10; ++i) src.decrement(); }, "D").start();
    }

}
